package logic

import (
	"context"
	"fmt"
	"zhihu/models/cache"
	"zhihu/models/mysql"
	"zhihu/pkg"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 用户登录注册
func (l *UserLoginLogic) UserLogin(in *zhihurpc.UserLoginSendSmsRequest) (*zhihurpc.UserLoginSendSmsResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	mysql.DB.Debug().Where("mobile = ?", in.Mobile).Find(&user)
	if user.ID == 0 {
		register := mysql.User{
			Mobile:   in.Mobile,
			Password: pkg.Md5(in.Password),
		}
		mysql.DB.Create(&register)
	}

	sendSmsCode := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Val()
	if sendSmsCode != in.SendSmsCode {
		return nil, fmt.Errorf("验证码输入错误")
	}

	return &zhihurpc.UserLoginSendSmsResponse{
		Id: int64(user.ID),
	}, nil
}
